<!-- 测评分类管理 -->

<template>
  <div>
    <el-breadcrumb :separator-icon="ArrowRight">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>心理测评</el-breadcrumb-item>
      <el-breadcrumb-item>测评分类管理</el-breadcrumb-item>
    </el-breadcrumb>
    <hr />

    <!-- 头部搜索栏 -->
    <div>
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="分类">
          <el-select
            v-model="formInline.classifyName"
            placeholder="请选择分类"
            clearable
            @clear="handleClear3()"
          >
            <el-option v-for="option in nameList" :key="option.id" :value="option.classifyName" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="getDuo">搜索</el-button>
          <el-button type="success" @click="dialogFormVisible = true">新增分类</el-button>
          <el-button type="danger" @click="delIds()">批量删除</el-button>
        </el-form-item>
      </el-form>

      <!-- 新增分类 -->
      <el-dialog v-model="dialogFormVisible" title="新增分类" width="730px">
        <el-form :model="form">
          <el-form-item label="分类名" :label-width="formLabelWidth">
            <el-input v-model="form.classifyName" placeholder="请输入分类名" />
          </el-form-item>
          <el-form-item label="分类封面图" :label-width="formLabelWidth">
            <el-upload
              class="avatar-uploader"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleFileChange"
              name="file"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer" style="text-align: center">
            <el-button @click="addNo()">取消</el-button>
            <el-button type="primary" @click="addYes()"> 确定 </el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 编辑与删除 -->
      <el-dialog v-model="edit" title="编辑测评" width="730px" id="selDialog">
        <el-form :model="editForm">
          <el-form-item label="测评题目" :label-width="formLabelWidth">
            <el-input v-model="editForm.classifyName" placeholder="请输入测评题目" />
          </el-form-item>
          <el-form-item label="测评封面图" :label-width="formLabelWidth">
            <el-upload
              class="avatar-uploader"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleFileChange"
              name="file"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer" style="text-align: center">
            <el-button @click="editNo()">取消</el-button>
            <el-button type="primary" @click="editYes()"> 确定 </el-button>
          </div>
        </template>
      </el-dialog>
    </div>

    <!-- 表格数据展示 -->
    <div>
      <el-table
        :data="tableData"
        border
        @selection-change="handleSelectionChange"
        style="width: 95%; margin-left: 30px"
      >
        <el-table-column :selectable="selectable" type="selection" width="55" />
        <el-table-column label="ID" width="120">
          <template #default="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column property="classifyName" label="分类名" />
        <el-table-column property="url" label="封面图">
          <template #default="scope">
            <el-image
              v-if="scope.row.url"
              :src="scope.row.url"
              style="width: 100px; height: 100px"
            />
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.$index, scope.row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.$index, scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页设置 -->
    <div>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]"
        :size="size"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { getCurrentInstance, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import http from '@/util/http'
// 多条件下拉框接收选择数据
const formInline = reactive({
  classifyName: '',
})
// 修改初始定义（如果需要）
const nameList = reactive([])

// 设置表格接收数据
const tableData = reactive([])
// 接收新增数据
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
// 打开对话框
const openDialog = () => {
  dialogFormVisible.value = true
}

// 重置表单数据
const resetForm = () => {
  imageUrl.value = ''
  tempFile.value = null
  originalUrl.value = ''
  form.classifyName = ''
  form.url = ''
  editForm.classifyName = ''
  editForm.url = ''
}

// 页面挂载后加载数据
onMounted(() => {
  getData(), getClass()
})

// 清除输入框自动搜索
const handleClear1 = () => {
  formInline.evaluationName = ''
  getData()
}
const handleClear2 = () => {
  formInline.evaluationIntro = ''
  getData()
}
const handleClear3 = () => {
  formInline.classifyName = ''
  getData()
}

const form = reactive({})

const imageUrl = ref('') // 用于预览的图片URL
const tempFile = ref(null) // 临时存储上传的文件对象
const originalUrl = ref('') // 存储原始头像路径
const handleFileChange = (file) => {
  if (file) {
    tempFile.value = file.raw // 存储原始文件对象
    // 创建临时URL用于预览
    imageUrl.value = URL.createObjectURL(file.raw)
  }
}
const addNo = () => {
  dialogFormVisible.value = false
  ElMessage('取消添加')
  resetForm()
}

// 提交表单
const addYes = async () => {
  console.log('开始上传文件', tempFile.value) // 调试文件对象
  if (tempFile.value) {
    const formData = new FormData()
    formData.append('file', tempFile.value)
    const uploadRes = await http({
      url: 'upload',
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
    form.url =  uploadRes.data //编译上传数据库的路径
  } else {
    form.url = originalUrl.value
  }
  // 提交表单数据
  await http.post('TestClassify/add', {
    classifyName: form.classifyName,
    url: form.url,
  })
  ElMessage.success('新增成功')
  resetForm() //重置弹框
  getData() //获取全部数据
  dialogFormVisible.value = false
}

// 编辑与删除
const edit = ref(false)
const editForm = reactive({})
const handleEdit = async (index, row) => {
  await http.get(`TestClassify/findById/${row.id}`).then((resp) => {
    Object.assign(editForm, resp.data) // 填充表单数据
    originalUrl.value = editForm.url // 保存原始头像路径
    imageUrl.value = originalUrl.value // 初始化预览图片
    edit.value = true // 打开对话框
  })
}
const editNo = () => {
  edit.value = false
  ElMessage('取消编辑')
  editForm = {}
  imageUrl.value =originalUrl.value
  tempFile.value = null
}
const editYes = async () => {
  console.log('开始上传文件', tempFile.value) // 调试文件对象
  if (tempFile.value) {
    const formData = new FormData()
    formData.append('file', tempFile.value)
    const uploadRes = await http({
      url: 'upload',
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
    editForm.url = uploadRes.data //编译上传数据库的路径
  } else {
    editForm.url = originalUrl.value //如果没有改变图片，那么就使用原始路径
  }
  //提交编辑
  await http
    .put('TestClassify/edit', {
      id: editForm.id,
      classifyName: editForm.classifyName,
      url: editForm.url,
    })
    .then((resp) => {
      if (resp.code == 200) {
        ElMessage({
          message: '修改成功！',
          type: 'success',
        })
        resetForm() //重置弹框
        getData() //获取全部数据
        edit.value = false //关闭对话框
      } else {
        ElMessage.error(resp.message)
      }
    })
    .catch((error) => {
      console.error('Error:', error)
      ElMessage.error('请求失败，请稍后再试')
    })
}
const handleDelete = (index, row) => {
  ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      axios
        .delete(`TestClassify/del/${row.id}`)
        .then((resp) => {
          if (resp.code == 200) {
            ElMessage({
              message: '删除成功',
              type: 'success',
            })
          } else {
            ElMessage.error(resp.message)
          }
        })
        .catch((error) => {
          console.error('Error:', error)
          ElMessage.error('请求失败，请稍后再试')
        })
        .finally(() => {
          getData()
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

// 批量删除
const multipleSelection = ref([])
const ids = ref('')
const delIds = () => {
  if (multipleSelection.value.length == 0) {
    ElMessage('请选择要删除的数据！')
  } else {
    ElMessageBox.confirm('此操作将永久删除该数据, 是否继续??', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        ids.value = multipleSelection.value.map((row) => row.id).join(',')
        console.log(ids.value)
        http
          .delete(`TestClassify/delBatch?ids=${ids.value}`)
          .then((resp) => {
            console.log(resp)
            if (resp.code == 200) {
              ElMessage({
                type: 'success',
                message: resp.message,
              })
            } else {
              ElMessage.error(resp.message)
            }
          })
          .catch((error) => {
            console.error('Error:', error)
            ElMessage.error('请求失败，请稍后再试')
          })
          .finally(() => {
            getData()
          })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
  }
}
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 设置分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const handleSizeChange = (val) => {
  console.log(`${val} items per page`)
  pageSize.value = val
  getData()
}
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`)
  currentPage.value = val
  getData()
}

// 获取axios对象实例发送请求
const axios = getCurrentInstance().appContext.config.globalProperties.axios
// 获取表单数据
const getData = async () => {
  try {
    const res = await http.get('TestClassify/findPage', {
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
      },
    })
    if (res.data) {
      tableData.splice(0, tableData.length, ...res.data.list)
    } else {
      console.error('返回数据格式错误:', res.data)
      tableData.splice(0, tableData.length) // 清空表格
    }
    total.value = res.data?.total || 0
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败，请稍后重试')
  }
}
//多条件
const getDuo = async () => {
  if (formInline.classifyName == '') {
    ElMessage.error('请输入分类名称')
    return
  }
  try {
    const resp = await http.get('TestClassify/findByName', {
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        classifyName: formInline.classifyName,
      },
    })
    if (Array.isArray(resp.data?.list)) {
      tableData.splice(0, tableData.length, ...resp.data.list)
      total.value = resp.data.total || 0
    } else {
      ElMessage.error('获取数据失败，返回格式不正确')
      tableData.splice(0, tableData.length) // 清空表格
    }
  } catch (error) {
    ElMessage.error('获取数据失败，请稍后重试')
    tableData.splice(0, tableData.length)
  }
}
// 获取分类数据
const getClass = () => {
  axios.get('TestClassify/findAllName').then((resp) => {
    console.log(resp.data)
    nameList.splice(0, nameList.length, ...resp.data);
  })
}
</script>

<style scoped>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

/* 图片显示 */
.block {
  /* border: 1px solid #ccc; */
  width: 100px;
  height: 100px;
  background-color: rgb(245, 247, 250);
  text-align: center;
  line-height: 100px;
}

/* 文件上传 */
.avatar-uploader .avatar {
  width: 150px;
  height: 150px;
  display: block;
  border-radius: 5px;
  margin-right: 5px;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
button{
  padding: 16px;
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  background-color: rgb(251, 253, 255);
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  text-align: center;
  border: 1px dashed rgb(192, 204, 218);
  border-radius: 5px;
}
</style>